<?php

namespace app\admin\service;

use app\admin\jwt\MyJwt;

class AuthService
{
    /**
     * 生成JWT token
     * @param array $payload 载荷数据
     * @return string
     */
    public function generateToken(array $payload)
    {
        return MyJwt::signToken($payload);
    }

    /**
     * 验证JWT token
     * @param string $token
     * @return array
     */
    public function verifyToken(string $token)
    {
        return MyJwt::checkToken($token);
    }

    /**
     * 将token加入黑名单
     * @param string $token
     * @return bool
     */
    public function addToBlacklist(string $token)
    {
        return MyJwt::addToBlacklist($token);
    }

    /**
     * 生成登录token
     * @param array $user 用户信息
     * @return array
     */
    public function generateLoginToken(array $user)
    {
        $payload = [
            'id' => $user['id'],
            'username' => $user['username'],
            'role' => $user['role'] ?? 1
        ];

        $token = $this->generateToken($payload);

        return [
            'token' => $token,
            'expire' => config('jwt.expire', 7200)
        ];
    }

    /**
     * 生成注册token
     * @param array $user 用户信息
     * @return array
     */
    public function generateRegisterToken(array $user)
    {
        $payload = [
            'user_id' => $user['id'],
            'username' => $user['username'],
            'role' => $user['role'] ?? 0
        ];

        $token = $this->generateToken($payload);

        return [
            'token' => $token,
            'expire' => config('jwt.expire', 7200)
        ];
    }
}
